package com.example.musiccommunity;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.Toolbar;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.aip.util.Base64Util;
import com.example.musiccommunity.util.ImageUtil;
import com.google.android.material.imageview.ShapeableImageView;

import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends AppCompatActivity {
    private LinearLayoutCompat main;
    private Toolbar toolbar;
    private ShapeableImageView img;
    private TextView choose;
    private EditText etUsername;
    private EditText etEmail;
    private EditText etPassword;
    private Button regist;

    private Bitmap bp = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);



        main = findViewById(R.id.main);
        toolbar = findViewById(R.id.toolbar);
        img = findViewById(R.id.img);
        choose = findViewById(R.id.choose);
        etUsername = findViewById(R.id.et_username);
        etEmail = findViewById(R.id.et_email);
        etPassword = findViewById(R.id.et_password);
        regist = findViewById(R.id.regist);


        BitmapDrawable bd = (BitmapDrawable) img.getDrawable();
        bp = bd.getBitmap();

        choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, 1);
            }
        });
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        regist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(etUsername.getText().toString().isEmpty() ||
                        etEmail.getText().toString().isEmpty() ||
                        etPassword.getText().toString().isEmpty() ){
                    Toast.makeText(RegisterActivity.this, "数据不能为空", Toast.LENGTH_SHORT).show();
                    return ;
                }
                reqString();
            }
        });
    }
    void reqString(){//用户注册
        //bp=ImageUtil.compressImage(bp);
        byte[] bytes1 = ImageUtil.getBytesByBitmap(bp);
        String image1 = Base64Util.encode(bytes1);
        String url=MainActivity.ip+"/user/add";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // 处理响应
                        String s=response;
                        Log.d("***********",s.toString());
                        if(s.toString().equals("success")){
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }else{
                            Toast.makeText(RegisterActivity.this, "注册失败，用户名或已存在!", Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 处理错误
                        Log.d("--------",error.getMessage().toString());
                        Toast.makeText(RegisterActivity.this, "注册失败，用户名或已存在", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("name", etUsername.getText().toString());
                params.put("psw", etPassword.getText().toString());
                params.put("email",etEmail.getText().toString());
                params.put("type", "用户");
                params.put("avatarBase64", image1); // 将 Base64 字符串作为参数传递
                return params;
            }
        };
        MainActivity.requestQueue.add(stringRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Uri u = data.getData();
            ContentResolver cr = RegisterActivity.this.getContentResolver();
            try {
//                Bitmap bit = BitmapFactory.decodeStream(cr.openInputStream(u));
//                BitmapDrawable bd=new BitmapDrawable(bit);
//                bp=bd.getBitmap();
//                img.setImageDrawable(bd);
                Bitmap bit = BitmapFactory.decodeStream(cr.openInputStream(u));
                BitmapDrawable bd=new BitmapDrawable(bit);
                img.setImageDrawable(bd);
                new Thread(() -> {
                    bp= ImageUtil.compressImage(bd.getBitmap());
                    new Handler(Looper.getMainLooper()).post(() -> {
                    });
                }).start();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}